﻿using DreamCMS.BLL.Factory;
using DreamCMS.BLL.Factory.Interface;
using DreamCMS.Entity;
using DreamCMS.WebCore.Common;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace DreamCMS.BLL
{
    public class TagManager
    {
        #region Init
        static ITagDAO dao = DataAccessFactory.CreateTagDAO();

        /// <summary>
        /// 标签列表
        /// </summary>
        private static List<TagInfo> tagsList = null;

        private static object lockHelper = new object();

        /// <summary>
        /// 初始化
        /// </summary>
        public static void InitTag()
        {
            if (tagsList == null)
            {
                lock (lockHelper)
                {
                    if (tagsList == null)
                    {
                        tagsList = dao.GetTagList();
                    }
                }
            }
        }
        /// <summary>
        /// 更新缓存，重新从数据库读取数据
        /// </summary>
        public static void ClearCache()
        {
            tagsList = dao.GetTagList();
        }
        /// <summary>
        /// 获取全部标签列表(所有Manager类中，选择全部的操作都要检查缓存是否为空)
        /// </summary>
        private static List<TagInfo> Tags
        {
            get
            {
                if (tagsList == null)
                {
                    InitTag();
                }
                return tagsList;
            }
        }
        #endregion

        #region Get
        /// <summary>
        /// 获取全部(所有Manager类中，选择全部的操作都要检查缓存是否为空)
        /// </summary>
        /// <returns></returns>
        public static List<TagInfo> GetTagList()
        {
            return Tags; //Tags内部会检查缓存是否为空
        }
        /// <summary>
        /// 根据ID获取标签
        /// </summary>
        /// <param name="Tagid"></param>
        /// <returns></returns>
        public static TagInfo GetTag(long Tagid)
        {
            if (TagManager.tagsList == null)
            {
                TagManager.InitTag();
            }
            foreach (TagInfo t in Tags)
            {
                if (t.Tagid == Tagid)
                {
                    return t;
                }
            }
            return null;
        }

        /// <summary>
        /// 根据标签名获取标签（用户获取标签ID构造文章的存储序列）
        /// </summary>
        /// <param name="name">标签名称</param>
        /// <returns>标签实体</returns>
        public static TagInfo GetTag(string name)
        {
            if (TagManager.tagsList == null)
            {
                TagManager.InitTag();
            }
            foreach (TagInfo t in Tags)
            {
                if (t.Name == name)
                {
                    return t;
                }
            }
            return null;
        }

        /// <summary>
        /// 根据标签别名获取标签
        /// </summary>
        /// <param name="slug">别名</param>
        /// <returns>标签实体</returns>
        public static TagInfo GetTagBySlug(string slug)
        {
            if (TagManager.tagsList == null)
            {
                TagManager.InitTag();
            }
            foreach (TagInfo t in Tags)
            {
                if (!string.IsNullOrEmpty(slug) && t.Slug.ToLower() == slug.ToLower())
                {
                    return t;
                }
            }
            return null;
        }


        /// <summary>
        /// 获取指定条数标签(按时间先后)
        /// </summary>
        /// <param name="rowCount">条数</param>
        /// <returns>标签实体集合</returns>
        public static List<TagInfo> GetTagList(int rowCount)
        {
            if(TagManager.tagsList==null)
            {
                TagManager.InitTag();
            }
            if (Tags.Count <= rowCount)
            {
                return Tags;
            }
            else
            {
                List<TagInfo> list = new List<TagInfo>();
                for (int i = 0; i < rowCount; i++)
                {
                    list.Add(Tags[i]);
                }
                return list;
            }
        }

        /// <summary>
        /// 获取分页标签
        /// </summary>
        /// <param name="pageSize"></param>
        /// <param name="pageIndex"></param>
        /// <param name="recordCount"></param>
        /// <returns></returns>
        public static List<TagInfo> GetTagList(int pageSize, int pageIndex, out int recordCount)
        {
            if(TagManager.tagsList==null)
            {
                TagManager.InitTag();
            }
            recordCount = Tags.Count;
            List<TagInfo> rlist = new List<TagInfo>();
            int start = (pageIndex - 1) * pageSize;
            int end = start + pageSize;
            if (end > Tags.Count)
            {
                end = Tags.Count;
            }
            for (int i = start; i < end; i++)
            {
                rlist.Add(Tags[i]);
            }
            return rlist;
        }



        /// <summary>
        /// 根据标签别名获取ID
        /// </summary>
        /// <param name="slug">别名</param>
        /// <returns>ID号</returns>
        public static long GetTagid(string slug)
        {
            if (TagManager.tagsList == null)
            {
                TagManager.InitTag();
            }
            foreach (TagInfo t in Tags)
            {

                if (!string.IsNullOrEmpty(slug) && t.Slug.ToLower() == slug.ToLower())
                {
                    return t.Tagid;
                }
            }
            return 0;
        }

        /// <summary>
        /// 根据标签ID来获取标签名称
        /// </summary>
        /// <param name="Tagid">标签ID</param>
        /// <returns>标签名</returns>
        public static string GetTagName(int Tagid)
        {
            if(TagManager.tagsList==null)
            {
                TagManager.InitTag();
            }
            foreach (TagInfo t in Tags)
            {
                if (t.Tagid == Tagid)
                {
                    return t.Name;
                }
            }
            return string.Empty;
        }

        /// <summary>
        /// 根据序列化的标签Id字符串来获取对应的所有标签的列表
        /// </summary>
        /// <param name="ids">标签Id,逗号隔开</param>
        /// <returns></returns>
        public static List<TagInfo> GetTagList(string ids)
        {
            if(TagManager.tagsList==null)
            {
                TagManager.InitTag();
            }

            List<TagInfo> list = GetTagList();

            List<TagInfo> list2 = new List<TagInfo>();

            string[] tempids = ids.Split(',');

            foreach (string str in tempids)
            {
                foreach (TagInfo tag in list)
                {
                    if (tag.Tagid.ToString() == str)
                    {
                        list2.Add(tag);
                        continue;
                    }
                }
            }
            return list2;
        }
        #endregion

        #region Update
        /// <summary>
        /// 修改标签（这种完全实体的修改，只需要更新数据库，因为客户传入形参就是缓存的对象）
        /// 但UserManager中的某用户统计文章数更新只传入更新一个字段，则需要同步更新缓存和数据库。
        /// </summary>
        /// <param name="tag"></param>
        /// <returns>返回修改的TagID号</returns>
        public static bool UpdateTag(TagInfo tag)
        {
            if (dao.UpdateTag(tag) > 0)
            {
                Tags.Sort();
                return true;
            }
            //如果更新失败还要回滚缓存中的标签纪录
            tag = dao.GetTag(tag.Tagid);
            Tags.Sort();
            return false;
        }
        /// <summary>
        /// 更新标签对应{}{}{}这种标签序列的每个标签的文章数（{}已经是数据库中格式化好的，不需要特殊处理）
        /// </summary>
        /// <param name="Tagids">格式:{2}{26}</param>
        /// <param name="addCount">标签对应的文章增加数（一般是添加一篇文章时调用，故值常是1）</param>
        /// <returns>是否更新成功</returns>
        public static bool UpdateTagUseCount(string Tagids, int addCount)
        {
            if (string.IsNullOrEmpty(Tagids))
            {
                return false;
            }

            string[] Tagidlist = Tagids.Replace("{", "").Split('}');
            bool flag = true;
            foreach (string Tagid in Tagidlist)
            {
                TagInfo tag = TagManager.GetTag(StringHelper.StrToInt64(Tagid, 0));
                if (tag != null)
                {
                    tag.Postcount += addCount;
                    if (dao.UpdateTag(tag) < 1)
                    {
                        //数据库那边的数量更新失败，则缓存要回滚
                        tag.Postcount -= addCount;
                        flag = false;
                    }
                }
                else
                {
                    flag = false;
                }
            }
            tagsList.Sort();
            return flag;
        }
        #endregion

        #region Insert
        /// <summary>
        /// 插入一条新标签记录
        /// </summary>
        /// <param name="tag">标签实体</param>
        /// <returns>返回插入的新纪录的ID号</returns>
        public static long InsertTag(TagInfo tag)
        {
            tag.Tagid = dao.InsertTag(tag);
            if (tag.Tagid > 0) //只有插入数据库成功，才插入缓存。
            {
                Tags.Add(tag); //同步插入到缓存
                Tags.Sort();
            }
            return tag.Tagid;
        }
        #endregion

        #region Delete
        /// <summary>
        /// 删除标签
        /// </summary>
        /// <param name="Tagid"></param>
        /// <returns></returns>
        public static bool DeleteTag(long Tagid)
        {
            //Tags.RemoveAll(delegate(TagInfo tag) { return tag.Tagid == Tagid; });  TagID不可能重复，用这方法有病吧
            if (dao.DeleteTag(Tagid) > 0)
            {
                Tags.Remove(TagManager.GetTag(Tagid));
                return true;
            }
            return false;
        }
        #endregion

    }
}
